package com.xuyang.fragment;

import java.io.IOException;
import java.util.ArrayList;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bookmanager.R;
import com.example.bookmanager.SelectBookActivity;
import com.xuyang.utils.DataBaseHelper;
import com.xy.custom.SelectHistoryMenu;
import com.xy.custom.SelectHistoryMenu.OnSelectHistoryMenuItemClickListener;
import com.xy.custom.SelectHistoryMenu.OnSelectHistoryMenuItemDeleteListener;

public class SelectFragment extends Fragment {
	ArrayList<String> books=new ArrayList<String>();
	private TextView txtSelect;
	private AutoCompleteTextView autoCompleteTextView;
	private DataBaseHelper dataBaseHelper;
	
	private SharedPreferences sp;
	private ArrayList<String> history;
	private ImageView imgDeleteHistory;
	
	private SelectHistoryMenu mSelectHistoryMenu;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view=inflater.inflate(R.layout.fragment_select, container, false);
		findViewsById(view);
		init();
		return view;
	}
	private void findViewsById(View view) {
		txtSelect=(TextView) view.findViewById(R.id.txt_select);
		autoCompleteTextView=(AutoCompleteTextView) view.findViewById(R.id.auto_complete_edittext);
		imgDeleteHistory=(ImageView) view.findViewById(R.id.img_delete_history);
		
		mSelectHistoryMenu=(SelectHistoryMenu) view.findViewById(R.id.select_history_menu);
	}
	private void init(){
		dataBaseHelper=new DataBaseHelper(getActivity());
		//如果数据库不存在，则创建数据库
		dataBaseHelper.createDataBase();
		dataBaseHelper.openDataBase();
		books=dataBaseHelper.getData();
		autoCompleteTextView.setThreshold(1);
		autoCompleteTextView.setAdapter(new ArrayAdapter<String>(getActivity(), R.layout.layout_auto_item, R.id.txt_auto_item, books));
		txtSelect.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String book=autoCompleteTextView.getEditableText().toString();
				if ("".equals(book)) {
					Toast.makeText(getActivity(), "请输入书名", 0).show();
					return ;
				}
				Intent intent=new Intent(getActivity(),SelectBookActivity.class);
				intent.putExtra("bookName", book);
				startActivity(intent);
				if (history.size()==11) {
					history.remove(10);
				}
				history.add(book);
				ObjectMapper oj=new ObjectMapper();
				String json = null;
				try {
					json = oj.writeValueAsString(history);
				} catch (JsonGenerationException e) {
					e.printStackTrace();
				} catch (JsonMappingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				sp.edit().putString("history",json).commit();
				mSelectHistoryMenu.notifyDataSetChanged();
				autoCompleteTextView.getEditableText().clear();
			}
		});
		autoCompleteTextView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String book=autoCompleteTextView.getEditableText().toString();
				Intent intent=new Intent(getActivity(),SelectBookActivity.class);
				intent.putExtra("bookName", book);
				startActivity(intent);
				if (history.size()==11) {
					history.remove(10);
				}
				history.add(book);
				ObjectMapper oj=new ObjectMapper();
				String json = null;
				try {
					json = oj.writeValueAsString(history);
				} catch (JsonGenerationException e) {
					e.printStackTrace();
				} catch (JsonMappingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				sp.edit().putString("history",json).commit();
				mSelectHistoryMenu.notifyDataSetChanged();
				autoCompleteTextView.getEditableText().clear();
			}
		});
		sp=getActivity().getSharedPreferences("history_select", getActivity().MODE_PRIVATE);
		String json=sp.getString("history", null);
		if (null!=json) {
			ObjectMapper oj=new ObjectMapper();
			try {
				history=oj.readValue(json, ArrayList.class);
			} catch (JsonParseException e) {
				e.printStackTrace();
			} catch (JsonMappingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else {
			history=new ArrayList<String>();
		}
		mSelectHistoryMenu.setDatas(history);
		mSelectHistoryMenu.setOnSelectHistoryMenuItemClickListener(new OnSelectHistoryMenuItemClickListener() {
			@Override
			public void onItemClick(View v) {
				String book=((TextView)v).getText().toString();
				Intent intent=new Intent(getActivity(),SelectBookActivity.class);
				intent.putExtra("bookName", book);
				startActivity(intent);
				history.remove(book);
				history.add(book);
				ObjectMapper oj=new ObjectMapper();
				String json = null;
				try {
					json = oj.writeValueAsString(history);
				} catch (JsonGenerationException e) {
					e.printStackTrace();
				} catch (JsonMappingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				sp.edit().putString("history",json).commit();
				mSelectHistoryMenu.notifyDataSetChanged();
			}
		});
		mSelectHistoryMenu.setOnMenuItemDeleteListener(new OnSelectHistoryMenuItemDeleteListener() {
			@Override
			public void onDeleteClick(String s) {
				history.remove(s);
				ObjectMapper oj=new ObjectMapper();
				String json = null;
				try {
					json = oj.writeValueAsString(history);
				} catch (JsonGenerationException e) {
					e.printStackTrace();
				} catch (JsonMappingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				Log.e("json", json);
				sp.edit().putString("history",json).commit();
			}
		});
		imgDeleteHistory.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(getActivity())
				.setTitle("提示消息")
				.setMessage("确认删除历史搜索？")
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						sp.edit().clear().commit();
						history.clear();
						mSelectHistoryMenu.notifyDataSetChanged();
					}
				})
				.setNegativeButton("取消", null)
				.create()
				.show();
			}
		});
	}
}
